package de.upb.messerschmidt.set;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.upb.messerschmidt.set.entity.Attendee;
import de.upb.messerschmidt.set.entity.Event;
import de.upb.messerschmidt.set.entity.EventStatus;
import de.upb.messerschmidt.set.entity.Person;
import de.upb.messerschmidt.set.jdo.PMF;
import de.upb.messerschmidt.set.util.Utils;

/**
 * Registers the {@link Attendee} information for specific {@link Event}s.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class RegisterAttendEventServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String eventString = req.getParameter("event");
		String personString = req.getParameter("person");
		String statusString = req.getParameter("status");

		// Split the input
		String eventParam = eventString.split(" at")[0];

		boolean exists = false;

		if (eventString == null || personString == null || statusString == null) {
			resp.setStatus(400);
			resp.getWriter().println(
					"Registration failed - please fill in all fields");
		} else {
			Event event = null;

			PersistenceManager pm = PMF.get().getPersistenceManager();

			Query query = pm.newQuery(Event.class);
			query.setFilter("title == titleParam");
			query.declareParameters("String titleParam");
			query.setOrdering("title desc");

			List<Event> results = (List<Event>) query.execute(eventParam);

			if (!results.isEmpty()) {
				event = results.get(0);
			}

			String[] name = Utils.nameParser(personString);

			for (String s : event.getAttendees()) {
				if (s.contains(name[0]) && s.contains(name[1]))
					exists = true;
			}

			if (!exists) {
				Query personQuery = pm.newQuery(Person.class);
				personQuery
						.setFilter("name == nameParam && prename == prenameParam");
				personQuery
						.declareParameters("String nameParam, String prenameParam");
				personQuery.setOrdering("name desc");

				Person user = null;

				List<Person> persons = (List<Person>) personQuery.execute(
						name[0], name[1]);

				if (!persons.isEmpty()) {
					user = persons.get(0);
				}

				if (event != null && user != null) {
					pm.refresh(user);
					EventStatus status = null;

					try {
						status = new EventStatus(user, statusString,
								event.getTitle());
						user.getEvents().add(status);
						pm.makePersistent(user);
					} catch (Exception e) {
						e.printStackTrace();
						resp.setStatus(400);
						resp.getWriter().println("Registration failed");
					}

					if (status != null) {
						try {
							pm.refresh(user);
							pm.refresh(event);

							String userName = user.getPrename() + " "
									+ user.getName();

							Attendee attendee = new Attendee(userName,
									event.getTitle(), status.getStatus());
							event.getAttendees().add(userName);

							pm.makePersistent(attendee);
							pm.makePersistent(event);
							pm.flush();

							resp.setStatus(200);
							resp.getWriter().println(
									"Registered sucessfully for event");
						} catch (Exception e) {
							e.printStackTrace();
							resp.setStatus(400);
							resp.getWriter().println("Registration failed");
						} finally {
							pm.close();
						}
					}
				}
			} else {
				resp.setStatus(400);
				resp.getWriter().println("Already registered");
			}
		}
	}
}
